<?php
/***************************************************************************
 *
 *   copyright            : (C) 2011 Winds of Storm
 *
 *   $Id: smf_fal.php 131 2011-06-12 20:24:56Z stormerider $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

require($libdir . "db." . $phpEx);

$smf_prefix             = $config['FORUM_DB_PREFIX'];
$users_table            = $smf_prefix . "members";
$avatars_table          = $smf_prefix . "attachments";
$smilies_table          = $smf_prefix . "smileys";
$smile_pattern_field    = "code";
$smile_url_field        = "filename";

$smilies_path           = $config['FORUM_BASE_URL'] . "Smileys/default/";
if (isset($config['FORUM_SMILIES_PATH'])) {
    $smilies_path       = $config['FORUM_SMILIES_PATH'];
}
$avatars_html_path      = $config['FORUM_BASE_URL'] . "avatars/";
$avatars_upload_path    = $config['FORUM_BASE_URL'] . "attachments/";

//
// This function is from SMF 1.x Sources/Subs.php
//
//
// Removes special entities from strings.  Compatibility...
function un_htmlspecialchars($string) {
	return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)) + array('&#039;' => '\'', '&nbsp;' => ' '));
}

function getAvatar ($userinfo) {
    global  $db2;
    global  $config;
    global  $dbprefix;
    global  $avatars_upload_path;
    global  $avatars_html_path;
    global  $avatars_table;

    $sql        = "SELECT ID_ATTACH as av_id FROM $avatars_table WHERE ID_MSG=0 AND ID_MEMBER=" . $userinfo['user_id'];
    $str_sql    = ereg_replace("\t", "", $sql);
    $str_sql    = ereg_replace("\n", " ", $str_sql);
    addToLog("getAvatar: SQL -- $str_sql");
    $result = $db2->sql_query($sql);
    if (($a_row = $db2->sql_fetchrow($result)) != NULL) {
        $avatar = $config['FORUM_BASE_URL'] . "index.php?action=dlattach;attach={$a_row['av_id']};type=avatar";
    } else if ($userinfo['avatar'] != '') {
        $avatar = $userinfo['avatar'];
        if (!eregi('http://', $avatar)) {
            $avatar = $avatars_html_path . $avatar;
        }
    }

    return $avatar;
}

function getProfileURL($userinfo) {
    global  $config;

    $url    = $config['FORUM_BASE_URL'] . "index.php?action=profile;u=" . $userinfo['user_id'];
    return $url;
}

function checkAuth($username, $password, $modGroup, $checkAdmin) {
    // success: return user info array
    // failure: return error string
    global  $db2;
    global  $dbprefix;
    global  $users_table;

    if (!isset($config['FORUM_ADMIN_GROUP'])) {
        $adminGroup = 1;
    } else {
        $adminGroup = $config['FORUM_ADMIN_GROUP'];
    }

    $sql    = "SELECT *
            FROM
                $users_table AS u
            WHERE
                memberName LIKE '$username'";

    $str_sql    = ereg_replace("\t", "", $sql);
    $str_sql    = ereg_replace("\n", " ", $str_sql);
    addToLog("checkAuth: Login SQL -- $str_sql");

    $result = $db2->sql_query($sql);

    if (!$result) {
        addToLog("checkAuth: Login request failed from " . $_SERVER['REMOTE_ADDR'] . " (" . $_SERVER['HTTP_USER_AGENT'] . ") -- user $username");
        return "Error authenticating account, please try back later.";
    }

    $row = $db2->sql_fetchrow($result);
    if ($row == NULL) {
        addToLog("checkAuth: Login failed from " . $_SERVER['REMOTE_ADDR'] . " (" . $_SERVER['HTTP_USER_AGENT'] . ") -- user $username"); # . " -- pass $password");
        return "Error logging in: possible reasons are an invalid username or authentication failure.";
    }

    $sha_passwd = sha1(strtolower($row['memberName']) . un_htmlspecialchars(stripslashes($password)));
    if ($row['passwd'] != $sha_passwd) {
        addToLog("checkAuth: Login failed from " . $_SERVER['REMOTE_ADDR'] . " (" . $_SERVER['HTTP_USER_AGENT'] . ") -- user $username -- stored hash {$row['passwd']} -- user hash $sha_passwd"); # . " -- pass $password");
        return "Error logging in: possible reasons are an invalid username or authentication failure.";
    }

    if ($row['is_activated'] != 1) {
        addToLog("checkAuth: Login attempt from {$_SERVER['REMOTE_ADDR']} on inactive account $username");
        return "Error logging in: the account you are trying to use is not active. Please validate it and try again.";
    }

    $userinfo['user_id']    = $row['ID_MEMBER'];
    $userinfo['username']   = $row['memberName'];
    $userinfo['avatar']     = $row['avatar'];
    $userinfo['moderator']  = 0;
    if (($row['ID_GROUP'] == $modGroup) || ($row['additionalGroups'] == $modGroup)) {
        $userinfo['moderator']  = 1;
    } else {
        if (($row['ID_GROUP'] == $adminGroup) || ($row['additionalGroups'] == $adminGroup)) {
            $userinfo['moderator']  = 1;
        }
    }

    if ($checkAdmin && $row['ID_GROUP'] != $adminGroup && $row['additionalGroups'] != $adminGroup) {
        addToLog("checkAuth: Admin login attempt from {$_SERVER['REMOTE_ADDR']} on account $username -- ID_GROUP = {$row['ID_GROUP']}, admins = $adminGroup");
        return "Error logging in: account is not an administrator.";
    }

    $sql    = "UPDATE ${dbprefix}prefs SET user_lastvisit_chat=UNIX_TIMESTAMP(NOW()) WHERE user_id={$row['ID_MEMBER']}";
    $db2->sql_query($sql);

    return $userinfo;
}

function checkBoardBan($ip, $userid) {
    global  $db2;
    global  $dbprefix;

    // returns boolean result
    return FALSE;
}

function checkValidAlias($alias, $uid) {
    global  $db2;
    global  $dbprefix;

    // returns boolean result
    return TRUE;
}

function showModeratorGroups($gid) {
	global	$db2;
	global	$config;

    $sql	= "SELECT * FROM {$config['FORUM_DB_PREFIX']}membergroups ORDER BY ID_GROUP";
    addToLog("showModeratorGroups: $sql");
    $res	= $db2->sql_query($sql);
    $groups = '';
    while ($row = $db2->sql_fetchrow($res)) {
    	$groups .= "<option value={$row['ID_GROUP']}";
    	if ($row['ID_GROUP'] == $gid) {
    		$groups .= " SELECTED";
    	}
    	$groups .= ">{$row['groupName']}</option>\n";
    }

    return $groups;
}
